/**
 * @description 水印核心类
 * @author LeaFish <735683662@qq.com>
 * @date 2022-02-22
 * @param {string} [id="ps_watermark"] 水印元素ID
 * @param {object} [window=window] 目标window对象
 * @param {number} [height=80] 单个水印块高度
 * @param {number} [width=150] 单个水印块宽度
 * @param {number} [fontSize=13] 文本字体大小
 * @param {string} [color="rgba(100,100,100,0.2)"] 文本颜色
 */
function Watermark(options) {
  options = options || {};
  this.id = options.id || "ps_watermark";
  this.window = options.window || window;
  this.height = options.height || 80;
  this.width = options.width || 150; // 控制水印的间隙大小
  this.fontSize = options.fontSize || 13;
  this.color = options.color || "rgba(100,100,100,0.2)";

  this.document = this.window.document;
  this.canvas = null;
  this.ctx = null;
  this.text = "";
  this.mode = null;

  /**
   * @description 绘制水印
   * @author LeaFish <735683662@qq.com>
   * @date 2022-02-22
   */
  this._drawCanvas = function (windowWidth, windowHeight) {
    var canvasWidth = windowWidth;
    var canvasHeight = windowHeight;

    this.canvas = this.document.createElement("canvas");
    this.ctx = this.canvas.getContext("2d");

    // 获取设备像素比
    this.PIXEL_RATIO = (function () {
      var dpr = window.devicePixelRatio || 1;
      var bsr = this.ctx.webkitBackingStorePixelRatio ||
        this.ctx.mozBackingStorePixelRatio ||
        this.ctx.msBackingStorePixelRatio ||
        this.ctx.oBackingStorePixelRatio ||
        this.ctx.backingStorePixelRatio || 1;
      return dpr / bsr;
    }.bind(this))();

    // 适配高清屏，canvas内容的宽高是实际的宽高的PIXEL_RATIO倍
    this.canvas.width = canvasWidth * this.PIXEL_RATIO;
    this.canvas.height = canvasHeight * this.PIXEL_RATIO;
    this.canvas.style.width = canvasWidth + "px";
    this.canvas.style.height = canvasHeight + "px";
    // 缩放绘图
    this.ctx.setTransform(this.PIXEL_RATIO, 0, 0, this.PIXEL_RATIO, 0, 0);

    this.ctx.font = this.fontSize + "px 黑体";
    this.ctx.rotate(-20 * Math.PI / 180);
    this.ctx.fillStyle = this.color;

    // 绘制文字
    for (var y = 1; y < canvasHeight * 4 / this.height + 1; y++) {
      for (var x = 1; x < canvasWidth * 2 / this.width; x++) {
        this.ctx.fillText(this.text, (y % 2 ? 0 : this.width / 2) + x * this.width - canvasWidth, y * this.height);
      }
    }

    return this.canvas.toDataURL("image/png");
  };


  this._drawToFullScreen = function () {
    this._drawCanvas(window.innerWidth, window.innerHeight);
    this.canvas.id = this.id;
    this.canvas.style.position = "fixed";
    this.canvas.style.top = 0;
    this.canvas.style.left = 0;
    this.canvas.style.pointerEvents = "none"; // 蒙层事件穿透
    this.canvas.style.zIndex = 20000000;
    this.document.getElementById(this.id) && this.document.body.removeChild(document.getElementById(this.id));
    this.document.body.appendChild(this.canvas);
  }

  this._drawToFullPage = function () {
    var windowWidth = this.document.body.scrollWidth;
    var windowHeight = this.document.body.scrollHeight;
    this.document.getElementById(this.id) && this.document.body.removeChild(document.getElementById(this.id));
    var base64 = this._drawCanvas(windowWidth, windowHeight);

    var element = this.document.createElement("div");
    element.id = this.id;
    element.style.position = "absolute";
    element.style.left = 0;
    element.style.top = 0;
    element.style.width = windowWidth;
    element.style.height = windowHeight;
    element.style.pointerEvents = "none"; // 蒙层事件穿透
    element.style.zIndex = 20000000;
    element.style.width = "100%";
    element.style.overflow = "hidden";

    var img = this.document.createElement("img");
    img.src = base64;
    img.style.display = "block";
    img.style.width = "100%";
    element.appendChild(img);

    this.document.body.appendChild(element);
  }


  /**
   * @description 检查父页面是否已存在水印
   * @author LeaFish <735683662@qq.com>
   * @date 22/02/2022
   * @return {boolean}  
   */
  this.existInParent = function () {
    return this.window.parent && this.window.parent.document.getElementById(this.id);
  }

  /**
   * @description 加载水印
   * @author LeaFish <735683662@qq.com>
   * @date 2022-02-22
   * @param {string} [text] 水印文本
   * @param {string} [text="fullScreen"] 加载模式，默认fullScreen全屏覆盖 fullPage 全页面覆盖
   */
  this.load = function (text, mode) {
    this.text = text || "";
    this.mode = mode || "fullScreen";
    var drawFunc;
    switch (this.mode) {
      case "fullScreen": drawFunc = this._drawToFullScreen.bind(this); break;
      case "fullPage": drawFunc = this._drawToFullPage.bind(this); break;
    }
    if (drawFunc) {
      drawFunc();
      this.window.addEventListener("resize", drawFunc);
    }else{
      console.error("Invalid mode " + mode);
    }
  }
}

/**
 * @description PS页面加载水印专用执行函数
 * @author LeaFish <735683662@qq.com>
 * @date 22/02/2022
 * @return {*}  
 */
function loadWatermarkInPS() {
  var text = "默认水印文本";
  // 实例化
  var watermark = new Watermark();

  // 水印覆盖页眉的实现方式，缺陷：打印页面时将没有水印
  // var watermark = new Watermark({window: window.parent || window});

  // 执行环境中存在组件容器，或父页面中已存在水印，则不加载水印
  var cIframe = document.getElementById("ptifrmtgtframe");
  if (cIframe || watermark.existInParent()) return;

  // 方案一 从欢迎语中获取要作为水印的文本内容（不适用psc页面独立使用的场景）
  // var greetingElement = (cIframe ? document : window.parent.document).getElementsByClassName("greeting")[0];
  // if (greetingElement) {
  //   text = greetingElement.innerText.split("：")[1];
  //   watermark.load(text);
  // }

  // 方案二 从系统信息中获取用户ID (需开启Web 概要配置中“显示连接和系统信息”)
  // var envElement = (cIframe ? cIframe.contentWindow : window).document.getElementById(["pt_envinfo_" + window.winName]);
  // if (envElement) {
  //   text = envElement.getAttribute("user");
  //   watermark.load(text);
  // }

  // 方案三 通过Ajax异步请求IScript获取用户信息（推荐）
  var IScriptURL = "WBELIB_GPS.IScriptGetWatermark"; // 需自行实现,此处仅为示例地址
  var xhr = new XMLHttpRequest();
  xhr.open('GET', IScriptURL, false);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      text = xhr.responseText;
    }
    watermark.load(text);
  }
  xhr.send();
}

// 添加load事件监听，页面加载完成后加载水印
window.addEventListener("load", loadWatermarkInPS);